//
//  KLRenewViewController.m
//  KunLun
//
//  Created by Mac on 2018/1/10.
//  Copyright © 2018年 stoneobs@icloud.com. All rights reserved.
//

#import "KLRenewViewController.h"
#import "STActionSheet.h"
@interface KLRenewViewController ()<STActionSheetDelegate>
@property(nonatomic, strong) NSMutableArray                     *buttonArray;
@property(nonatomic, strong) NSMutableArray                     *carArray;

@property(nonatomic, strong) NSArray                     *dataArray;

@property(nonatomic, strong) NSMutableArray                     *stayArray;
@property(nonatomic, strong) NSMutableArray                     *especiallArray;
@property(nonatomic, strong) NSMutableArray                     *balnkArray;
@end

@implementation KLRenewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self sendFetchShopTypeMoneyRequest];
    self.title = @"店铺续费";
    self.buttonArray = [NSMutableArray new];
    self.carArray = [NSMutableArray new];
    //废弃
    self.stayArray = [NSMutableArray new];
    self.especiallArray = [NSMutableArray new];
    self.balnkArray = [NSMutableArray new];
    
    
    // Do any additional setup after loading the view.
}

#pragma mark --subView
- (void)configSubView{
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 30)];
    header.backgroundColor = [UIColor whiteColor];
    
    UIView * titleView = [KLUtils headerViewWithTitle:@"店铺到期时间"];
    titleView.backgroundColor = KL_backgroundColor;
    [header addSubview:titleView];
    
//    "id": 1,
//    "classify_id": "各地特产",
//    "expire_at": 1523181999
    
    CGFloat left = 0 ;
    CGFloat bootom= 0;
    for (int i = 0; i < self.dataArray.count; i++) {
        NSDictionary * dic = self.dataArray[i];
        NSString * title = dic[@"classify_id"];
        
        NSInteger  classID = [dic[@"id"] integerValue];
        NSInteger tag = classID + 10000;
        
        NSDate * date = [NSDate dateWithTimeIntervalSince1970:[dic[@"expire_at"] integerValue]];
        NSString * time = date.st_mmddByLineWithDate;
        time = [NSString stringWithFormat:@"%@过期",time];
        UIView * carView = [self viewWithTitle:title timeTitle:time tag:tag];
        carView.left = left;
        [header addSubview:carView];
        left = carView.right;
        bootom = carView.bottom;
    }
    
    
    UIView * timeView = [KLUtils headerViewWithTitle:@"续费中心"];
    timeView.top = bootom;
    timeView.backgroundColor = KL_backgroundColor;
    [header addSubview:timeView];
   //
    UIView *carTimeView = [self timeViewWithTitle:@"时间选择" array:self.carArray];
    carTimeView.top = timeView.bottom;
    [header addSubview:carTimeView];
//    UIView *stayTimeView = [self timeViewWithTitle:@"住宿" array:self.stayArray];
//    stayTimeView.top = carTimeView.bottom;
//    [header addSubview:stayTimeView];
//
//    UIView *escTimeView = [self timeViewWithTitle:@"特产" array:self.especiallArray];
//    escTimeView.top = stayTimeView.bottom;
//    [header addSubview:escTimeView];
//
//    UIView *blankTimeView = [self timeViewWithTitle:@"菜园子" array:self.balnkArray];
//    blankTimeView.top = escTimeView.bottom;
//    [header addSubview:blankTimeView];
    
    __weak typeof(self) weakSelf =  self;
    STButton * confimButton = [[STButton alloc] initWithFrame:CGRectMake(30, carTimeView.bottom + 40, UIScreenWidth - 60 , 44)
                                                        title:@"立即支付"
                                                   titleColor:[UIColor whiteColor]
                                                    titleFont:18
                                                 cornerRadius:10
                                              backgroundColor:KL_BlueBackGroundColor
                                              backgroundImage:nil
                                                        image:nil];
    [confimButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedConfimButton];
    }];
    confimButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [header addSubview:confimButton];
    
    header.height = confimButton.bottom + 20;
    self.tableView.tableHeaderView = header;
}
- (UIView*)timeViewWithTitle:(NSString*)title array:(NSMutableArray*)array{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 80)];
    view.backgroundColor = [UIColor whiteColor];
    
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(self.insetX, 0, UIScreenWidth, 44)
                                                     text:title
                                                textColor:KL_BlueBackGroundColor
                                                     font:16
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    [view addSubview:titleLable];
    CGFloat ceterX = UIScreenWidth / 8;
    NSArray * titleArray = @[@"1天",@"10天",@"20天",@"30天",@"90天",@"183天",@"365天"];
    __weak typeof(self) weakSelf =  self;
    for (NSInteger i = 0; i < titleArray.count; i ++) {
        CGFloat with = UIScreenWidth / 4;
        
        STButton * buyButton = [[STButton alloc] initWithFrame:CGRectMake(0, titleLable.bottom, with - 20, 31)
                                                         title:titleArray[i]
                                                    titleColor:KL_firstTextColor
                                                     titleFont:15
                                                  cornerRadius:5
                                               backgroundColor:KL_backgroundColor
                                               backgroundImage:nil
                                                         image:nil];
        buyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        buyButton.centerX = ceterX;
        ceterX = ceterX + with;
        [buyButton setClicAction:^(UIButton *sender) {
            [weakSelf onSelectdButton:sender array:array];
        }];
        [view addSubview:buyButton];
        view.height = buyButton.bottom + 20;
        [array addObject:buyButton];
        if (i == 0) {
            [self onSelectdButton:buyButton array:array];
        }
        if (i >3) {
            buyButton.top = titleLable.bottom + 31 + 10;
            buyButton.left = i%4  * with + 10;
        }
        view.height = buyButton.bottom + 20;
    }
    return view;
}
- (UIView*)viewWithTitle:(NSString*)title timeTitle:(NSString*)timeTitle tag:(NSInteger)tag{
    
    CGFloat with = UIScreenWidth / 4;
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 44, with, 80)];
    STButton * buyButton = [[STButton alloc] initWithFrame:CGRectMake(10, 10, with - 20, 31)
                                                     title:title
                                                titleColor:KL_firstTextColor
                                                 titleFont:16
                                              cornerRadius:5
                                           backgroundColor:KL_backgroundColor
                                           backgroundImage:nil
                                                     image:nil];
    buyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    if ([title isEqualToString:@"民车出租"]) {
        buyButton.selected = YES;
    }
    buyButton.tag = tag;
    [self.buttonArray addObject:buyButton];
    [self refreshButton];
    __weak typeof(self) weakSelf =  self;
    [buyButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectdTypeButton:sender];
    }];
    [view addSubview:buyButton];
    
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(0, buyButton.bottom, with, 40)
                                                     text:timeTitle
                                                textColor:KL_secendTextColor
                                                     font:14
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentCenter];
    [view addSubview:titleLable];
    
    view.height = titleLable.bottom;

    return view;
}
- (void)onSelectdButton:(UIButton*)sender array:(NSArray*)array{
    for (UIButton * button in array) {
        button.selected = NO;
        sender.selected = YES;
        if (button.selected) {
            button.backgroundColor = KL_BlueBackGroundColor;
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }else{
            button.backgroundColor = KL_backgroundColor;
            [button setTitleColor:KL_firstTextColor forState:UIControlStateNormal];
        }
    }
}
- (NSString*)findDay{
    for (UIButton * button in self.carArray) {
        if (button.selected) {
            NSString * day = [button.currentTitle stringByReplacingOccurrencesOfString:@"天" withString:@""];
            return day;
        }
    }
    return @"";
}
- (NSArray*)findButtonSelecteNum{
    NSMutableArray * array = [NSMutableArray new];
    for (UIButton * button in self.buttonArray) {
        if (button.selected) {
            NSInteger num = button.tag - 10000;
            [array addObject:@(num).description];
        }
    }
    return array;
}
- (void)refreshButton{
    for (UIButton * button in self.buttonArray) {
        if (button.selected) {
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
            [button setBackgroundColor:KL_BlueBackGroundColor];
        }else{
            [button setTitleColor:KL_firstTextColor forState:UIControlStateNormal];
            [button setBackgroundColor:KL_backgroundColor];
        }
    }
}
- (void)onSelectdTypeButton:(UIButton*)sender{
    if ([self findButtonSelecteNum].count <= 1) {
        sender.selected = YES;
    }else{
        sender.selected = !sender.selected;
    }
    
    [self refreshButton];
}

- (void)onSelectedConfimButton{
    
    STActionSheet  * action = [STActionSheet actionSheetWithTitle:@"支付方式" buttonTitles:@[@"微信",@"支付宝"] cancelTitle:@"取消" delegate:self];
    [action show];
}
- (void)actionSheet:(STActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //微信
        [self sendXufeiRequestWithType:@"wxpay"];
    }
    if (buttonIndex == 1) {
        //支付宝
       [self sendXufeiRequestWithType:@"alipay"];
    }
}
#pragma mark --NetWork Method
- (void)sendFetchShopTypeMoneyRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if (self.shops_id.length) {
        [dic setObject:self.shops_id forKey:@"shop_id"];
    }
    [dic setObject:@"2" forKey:@"type"];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/shop/goodstype",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 
                                                 NSArray * dataArray =  responseObject[@"data"];
                                                 self.dataArray = dataArray;
                                                 [self configSubView];
                                                 
                                                 [SVProgressHUD dismiss];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 
                                             }];
}
- (void)sendXufeiRequestWithType:(NSString*)type{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/order/shoppay",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    if (type.length) {
        [dic setObject:type forKey:@"pay_type"];
    }
    NSString * day = [self findDay];
    if (day.length) {
        [dic setObject:day forKey:@"day"];
    }
    NSArray * array = [self findButtonSelecteNum];
    NSString * num = [array componentsJoinedByString:@","];
    [dic setObject:num forKey:@"classify"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSDictionary * dataDic =  responseObject[@"data"];
                                                 if ([dataDic.allKeys containsObject:@"pay_data"]) {
                                                     if ([type isEqualToString:@"wxpay"]) {
                                                         NSDictionary * wechatDic = dataDic[@"pay_data"];
                                                         //wechat
                                                         PayReq *request = [PayReq new];
                                                         request.nonceStr = wechatDic[@"noncestr"];
                                                         request.package = wechatDic[@"package"];
                                                         request.partnerId = wechatDic[@"partnerid"];
                                                         request.prepayId = wechatDic[@"prepayid"];
                                                         request.sign = wechatDic[@"sign"];
                                                         request.timeStamp = [wechatDic[@"timestamp"] intValue];
                                                         [WXApi sendReq:request];
                                                     }else{
                                                         NSString * alipayStr = dataDic[@"pay_data"];
                                                         //alipay
                                                         [[AlipaySDK defaultService] payOrder:alipayStr fromScheme:@"KunLun" callback:^(NSDictionary *resultDic) {
                                                             NSLog(@"reslut = %@",resultDic);
                                                             //回调在appdelegate 中
                                                         }];
                                                     }
                                                 }
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 
                                                 
                                             }];
}
@end
